/**
 * 
 */
package org.zxstudio.encrypt.utils;

import java.lang.ref.SoftReference;
import java.util.HashMap;

import org.zxstudio.encrypt.MediaBean;
import org.zxstudio.encrypt.R;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

public class LazyImageLoader {

	private static final String TAG = "LazyImageLoader";
	private static final boolean DEBUG = true;
	private Object mLock = new Object();

	private boolean mAllowLoad = true;

	private boolean firstLoad = true;

	private int mStartLoadLimit = 0;

	private int mStopLoadLimit = 0;

	final Handler mHandler = new Handler();
	private HashMap<String, SoftReference<Drawable>> mImageCache = new HashMap<String, SoftReference<Drawable>>();
	private HashMap<Uri, SoftReference<Drawable>> mVideoThumbCache = new HashMap<Uri, SoftReference<Drawable>>();
	private static LazyImageLoader mInstance = null;

	public interface OnImageLoaderListener {
		public void onImageLoad(ImageView t, Drawable drawable , int type);
		public void onImageLoad(ImageView t, Drawable drawable );
		public void onError(ImageView t);
	}

	public static LazyImageLoader getInstance() {
		if (mInstance == null) {
			return new LazyImageLoader();
		}
		return mInstance;
	}

	private void loadVideo(ImageView iv, String imagePath,
			OnImageLoaderListener listener , int type) {
		final OnImageLoaderListener mListener = listener;
		final String mImageUrl = imagePath;
		final ImageView view = iv;
		final int mimeType = type;
		new Thread() {

			@Override
			public void run() {
				super.run();
				if (!mAllowLoad) {
					synchronized (mLock) {
						try {
							mLock.wait();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}

				if (mAllowLoad) {
					loadVideo(mImageUrl, view, mListener,mimeType);
				}
			}

		}.start();
	}

	public void loadVideo(ImageView iv, String imagePath,
			OnImageLoaderListener listener ) {
		final OnImageLoaderListener mListener = listener;
		final String mImageUrl = imagePath;
		final ImageView view = iv;
		new Thread() {

			@Override
			public void run() {
				super.run();
				if (!mAllowLoad) {
					synchronized (mLock) {
						try {
							mLock.wait();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}

				if (mAllowLoad) {
					loadVideo(mImageUrl, view, mListener);
				}
			}

		}.start();
	}
	
	private void loadVideo(final String mImageUrl, final ImageView mt,
			final OnImageLoaderListener mListener) {
		if (mImageCache.containsKey(mImageUrl)) {
			SoftReference<Drawable> softReference = mImageCache.get(mImageUrl);
			final Drawable d = softReference.get();
			if (d != null) {
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						if (mAllowLoad) {
							mListener.onImageLoad(mt, d);
						}
					}

				});
				return;
			}
		}

		final Drawable d = createVideoThumbnail(mImageUrl);
		if (d != null) {
			mImageCache.put(mImageUrl, new SoftReference<Drawable>(d));
		}
		mHandler.post(new Runnable() {

			@Override
			public void run() {
				if (mAllowLoad) {
					mListener.onImageLoad(mt, d);
				}
			}

		});
	}
	
	private void loadVideo(final String mImageUrl, final ImageView mt,
			final OnImageLoaderListener mListener, final int type) {
		if (mImageCache.containsKey(mImageUrl)) {
			SoftReference<Drawable> softReference = mImageCache.get(mImageUrl);
			final Drawable d = softReference.get();
			if (d != null) {
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						if (mAllowLoad) {
							mListener.onImageLoad(mt, d, type);
						}
					}

				});
				return;
			}
		}

		final Drawable d = createVideoThumbnail(mImageUrl);
		if (d != null) {
			mImageCache.put(mImageUrl, new SoftReference<Drawable>(d));
		}
		mHandler.post(new Runnable() {

			@Override
			public void run() {
				if (mAllowLoad) {
					mListener.onImageLoad(mt, d , type);
				}
			}

		});
	}
	
	public void loadMedia(ImageView v, String path,
			OnImageLoaderListener listener , int type) {
		if (type == MediaBean.IMAGE) {
			v.setImageResource(R.drawable.icon_image);
			loadImage(v,path,listener,type);
		} else if (type == MediaBean.VIDEO){
			v.setImageResource(R.drawable.icon_video);
			loadVideo(v,path,listener,type);
		}
	}
	
	private void loadImage(ImageView v, String imagePath,
			OnImageLoaderListener listener , int type) {
		final OnImageLoaderListener mListener = listener;
		final String mImageUrl = imagePath;
		final ImageView view = v;
		final int mimeType = type;
		new Thread() {

			@Override
			public void run() {
				super.run();
				if (!mAllowLoad) {
					synchronized (mLock) {
						try {
							mLock.wait();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
				if (mAllowLoad) {
					loadImage(mImageUrl, view, mListener,mimeType);
				}
			}
		}.start();
	}
	
	public void loadImage(ImageView v, String imagePath,
			OnImageLoaderListener listener ) {
		final OnImageLoaderListener mListener = listener;
		final String mImageUrl = imagePath;
		final ImageView view = v;
		new Thread() {

			@Override
			public void run() {
				super.run();
				if (!mAllowLoad) {
					synchronized (mLock) {
						try {
							mLock.wait();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
				if (mAllowLoad) {
					loadImage(mImageUrl, view, mListener);
				}
			}
		}.start();
	}
	private void loadImage(final String mImageUrl, final ImageView mt,
			final OnImageLoaderListener mListener ,final int type) {
		if (mImageCache.containsKey(mImageUrl)) {
			SoftReference<Drawable> softReference = mImageCache.get(mImageUrl);
			final Drawable d = softReference.get();
			if (d != null) {
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						if (mAllowLoad) {
							mListener.onImageLoad(mt, d,type);
						}
					}

				});
				return;
			}
		}
		final Drawable d = loadImageByPath(mImageUrl);
		if (d != null) {
			mImageCache.put(mImageUrl, new SoftReference<Drawable>(d));
		}
		mHandler.post(new Runnable() {

			@Override
			public void run() {
				if (mAllowLoad) {
					mListener.onImageLoad(mt, d , type);
				}
			}

		});
	}

	private void loadImage(final String mImageUrl, final ImageView mt,
			final OnImageLoaderListener mListener) {
		if (mImageCache.containsKey(mImageUrl)) {
			SoftReference<Drawable> softReference = mImageCache.get(mImageUrl);
			final Drawable d = softReference.get();
			if (d != null) {
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						if (mAllowLoad) {
							mListener.onImageLoad(mt, d);
						}
					}

				});
				return;
			}
		}
		final Drawable d = loadImageByPath(mImageUrl);
		if (d != null) {
			mImageCache.put(mImageUrl, new SoftReference<Drawable>(d));
		}
		mHandler.post(new Runnable() {

			@Override
			public void run() {
				if (mAllowLoad) {
					mListener.onImageLoad(mt, d);
				}
			}

		});
	}
	
	private  Drawable createVideoThumbnail(String filePath) {
		Bitmap bm = ThumbnailUtils.createVideoThumbnail(filePath,
				Images.Thumbnails.MICRO_KIND);
		return new BitmapDrawable(bm);
	}

	public static BitmapDrawable getVideoThumbnail(ContentResolver cr, Uri uri) {
		Bitmap bitmap = null;
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inDither = false;
		options.inPreferredConfig = Bitmap.Config.ARGB_8888;
		// Uri uri = Uri.parse(path);
		Log.v(TAG, "getVideoThumbnail:uri:" + uri.toString());
		Cursor cursor = cr.query(uri,
				new String[] { MediaStore.Video.Media._ID }, null, null, null);

		if (cursor == null || cursor.getCount() == 0) {
			if (DEBUG) {
				Log.v(TAG, "getVideoThumbnail:cursor is null ");
			}
			return null;
		}
		if (DEBUG) {
			Log.v(TAG, "getVideoThumbnail:" + cursor.getCount());
		}
		cursor.moveToFirst();
		String videoId = cursor.getString(cursor
				.getColumnIndex(MediaStore.Video.Media._ID)); // image id in
																// image table.s

		if (videoId == null) {
			return null;
		}
		cursor.close();
		long videoIdLong = Long.parseLong(videoId);
		bitmap = MediaStore.Video.Thumbnails.getThumbnail(cr, videoIdLong,
				Images.Thumbnails.MICRO_KIND, options);

		return new BitmapDrawable(bitmap);
	}

	private Drawable loadImageByPath(String filePath) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.outHeight = 200;
		options.inJustDecodeBounds = true;

		// 获取这个图片的宽和高
		Bitmap bm = BitmapFactory.decodeFile(filePath, options); // 此时返回bm为空
		options.inJustDecodeBounds = false;
		int be = options.outHeight / 20;
		if (be % 10 != 0) {
			be += 10;
		}
		be = be / 10;
		if (be <= 0) {
			be = 1;
		}
		options.inSampleSize = be;
		bm = BitmapFactory.decodeFile(filePath, options);
		if (bm != null) {
			return new BitmapDrawable(bm);
		} else {
			return null;
		}
	/*	int w = bm.getWidth();
		int h = bm.getHeight();
		w = w * 200 / h;*/
		// view.setImageBitmap(bm);
		
	}

	public void restore() {
		mAllowLoad = true;
	}

	public void lock() {
		mAllowLoad = false;
	}

	public void unlock() {
		mAllowLoad = true;
		synchronized (mLock) {
			mLock.notifyAll();
		}
	}
}
